<template>
  <div class="app-container app-content">
    <div class="top-title">
      <span class="tinyTitle">
        <div class="titleFlag"></div>
        {{ salaryItem.title||"工作年限薪酬分布" }}
      </span>
    </div>
    <!-- <div class="top-line"></div> -->
    <template v-if="activeName == 'full'">
      <el-row class="search-container">
        <el-form ref="form" :model="form" label-width="auto">
          <el-form-item label="统计时间">
            <el-date-picker v-model="selectBetweenTime" :clearable="false" size="small" type="monthrange" align="right"
              unlink-panels value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始月份"
              end-placeholder="结束的月份" :picker-options="pickerOptions" @change="handleDateChange">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="工作经验">
            <workYearSearch ref="regionRef" @change="onWorkYearChange" />
          </el-form-item>
          <el-form-item label="区域名称">
            <regoinSearch ref="regionRef" @onRegionChange="onRegionChange" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="fetchData()">查询</el-button>
            <el-popover placement="top-start" width="200" trigger="hover" content="通过您的筛选条件，计算平均薪酬以及职位总数">
              <el-button slot="reference" type="primary" plain @click="fetchTotalData()"
                style="margin-left: 10px">计算查询结果
              </el-button>
            </el-popover>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="list">
        <el-tooltip effect="light" placement="top">
          <div class="toolTipGuide" slot="content">
            <div class="toolTipTitle"></div>
            <div class="toolTipItems" v-for="(item, index) in stepInfo" :key="index">
              <div class="stepImageContainer">
                <img :src="item.stepImage" class="stepImage" />
              </div>
              <div class="stepDesc">{{ item.stepDesc }}</div>
            </div>
          </div>
          <el-button size="mini" class="filter-item" icon="el-icon-download" @click="onExportClick">导出
          </el-button>
        </el-tooltip>
        <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row
          @sort-change="sortChange">
          <el-table-column label="区域名称">
            <template slot-scope="scope">
              {{ scope.row.salaryRegionName }}
            </template>
          </el-table-column>
          <el-table-column label="工作经验">
            <template slot-scope="scope">
              {{ scope.row.expCodeStr }}
            </template>
          </el-table-column>
          <el-table-column label="平均薪酬" prop="salary_num" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.salaryNum }}
            </template>
          </el-table-column>
          <el-table-column label="职位数量" prop="company_num" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.companyNum }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="统计时间"
            prop="generate_time"
            sortable="custom"
          >
            <template slot-scope="scope">
              {{ scope.row.generateTime.slice(0, 7) }}
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="tablePage.pageNum"
          :page-size="tablePage.pageSize" :page-sizes="pageSizes" :total="tablePage.total"
          @size-change="handleSizeChange" @current-change="handlePageChange" />
      </div>
    </template>
    <div class="echart" v-if="activeName == 'chart'">
      <div class="workBarChart">
        <workBarChart />
      </div>
    </div>
  </div>
</template>

<script>
import {
  getWorkSalaryList,
  getWorkSalaryTotalData,
  getWorkSalaryListExport,
} from "@/api/salary";
import SelectRegion from "@/components/SelectRegion";
import workBarChart from "@/views/position/components/workBarChart";
import regoinSearch from "@/views/position/components/regoinSearch";
import workYearSearch from "@/views/position/components/workYearSearch";

export default {
  name: "WorkSalary",
  components: { SelectRegion, regoinSearch, workYearSearch, workBarChart },
  props: {
    salaryItem: {
      type: Object,
      require: true,
    },
  },

  data() {
    return {
      regionBarDescAvg: "",
      form: {},
      list: null,
      totalData: {
        salaryNum: null,
        companyNum: null,
      },
      listLoading: true,
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 10, // 每页多少条
        total: 0, // 总记录数
      },
      positionName: "",
      selectTime: "",
      regionId: "",
      regionList: [],
      currentRegionName: "全国",
      currentChartRegionName: "全国",
      pageSizes: [10, 20, 30],
      workYearOptions: [
        { value: "", label: "全部" },
        { value: "10", label: "不限" },
        { value: "20", label: "0-1年" },
        { value: "30", label: "1-3年" },
        { value: "40", label: "3-5年" },
        { value: "50", label: "5-10年" },
        { value: "60", label: "10年+" },
      ],
      workYearValue: "",
      chartData: [],

      orderByColumn: "",
      groupByColumn: "exp_code",
      orderBy: "",

      selectBetweenTime: "",
      // 时间选择器
      pickerOptions: {
        shortcuts: [
          {
            text: "今年至今",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      activeName: "chart",
      stepInfo: [
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide1.png",
          stepDesc: "第一步，打开导出文件",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide2.png",
          stepDesc: "第二步，选择数据范围。",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide3.png",
          stepDesc: "第三步，选择全部图表",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide4.png",
          stepDesc: "第四步，选择自己需要的样式备份",
        },
        {
          stepImage:
            "https://img3.job1001.com/data_center/images/exportGuide5.png",
          stepDesc: "第五步，图表制作完成啦！",
        },
      ],
    };
  },
  created() {
    this.positionName = this.$route.query.name;
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    handleClick() {
      if (this.activeName == "full") {
        this.currentRegionName = "全国";
        this.groupByColumn = "exp_code";
        this.regionList = [];
        let date = new Date();
        let currentMonth = date.getMonth() + 1;
        let value =
          date.getFullYear() +
          "-" +
          (currentMonth < 10 ? "0" : "") +
          currentMonth +
          "-" +
          "01";

        // 默认显示上月日期
        let date1 = new Date();
        date1.setMonth(date1.getMonth() - 1); // 减去一个月
        let previousMonth = date1.getMonth() + 1;
        let value1 =
          date1.getFullYear() +
          "-" +
          (previousMonth < 10 ? "0" : "") +
          previousMonth +
          "-" +
          "01";

        // 确保selectBetweenTime中的日期按照从小到大的顺序排列
        this.selectBetweenTime = [value, value1].sort();
        this.workYearValue = "";
        this.fetchData();
      } else {
        this.groupByColumn = "";
      }
    },
    handleDateChange(val) {
      this.tablePage.pageNum = 1;
      this.fetchData();
    },
    onWorkYearChange(val) {
      this.workYearValue = val.value;
      //console.log(" this.workYearValue", this.workYearValue);
      this.tablePage.pageNum = 1;
      this.fetchData();
    },
    onRegionChange(val) {
      this.currentRegionName = val.label;
      this.regionList = [val.value];
      this.tablePage.pageNum = 1;
      this.fetchData();
    },
    fetchData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
        page: this.tablePage.pageNum,
        perPage: this.tablePage.pageSize,
      };
      if (this.selectTime != "") {
        params.selectTime = this.selectTime;
      }
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.workYearValue != "") {
        params.selectValue = this.workYearValue;
      }

      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }
      if (this.groupByColumn != null && this.groupByColumn != "") {
        params.groupByColumn = this.groupByColumn;
      }

      if (this.orderByColumn != "" && this.orderBy != "") {
        params.orderByColumn = this.orderByColumn;
        params.orderBy = this.orderBy == "ascending" ? "asc" : "desc";
      } else {
        params.orderByColumn = "salary_num";
        params.orderBy = "desc";
      }

      getWorkSalaryList(params).then((response) => {
        const count = response.data.count - 0;
        this.tablePage.total = count;
        this.list = response.data.rows;

        if (this.groupByColumn != "") {
          this.list.forEach((item) => {
            item.salaryRegionName =
              this.currentRegionName != "" && this.currentRegionName != null
                ? this.currentRegionName
                : "全国";
          });
        }
        this.listLoading = false;
      });
    },
    fetchTotalData() {
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
      };
      if (this.workYearValue != "") {
        params.selectValue = this.workYearValue;
      }
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.selectBetweenTime != null && this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }
      this.fetchData();
      getWorkSalaryTotalData(params).then((response) => {
        if (
          response.data != null &&
          response.data.companyNum != null &&
          response.data.salaryNum != null
        ) {
          this.totalData.salaryNum = parseFloat(
            response.data.salaryNum
          ).toFixed(2);
          this.totalData.companyNum = response.data.companyNum;
        } else {
          this.totalData.salaryNum = 0;
          this.totalData.companyNum = 0;
        }
        let content =
          `<div style='border-top:1px solid #e8e8e8;border-bottom:1px solid #e8e8e8;margin-top:-10px;font-size:14px;padding:28px 0;text-align:left;'>` +
          "<div style='font-size:16px;font-weight:bold;color:#222;margin-bottom:0px;'>通过您的查询条件（岗位，地区，时间）可得：</div>" +
          "<br/>" +
          "您查询的地区：[ " +
          (this.currentRegionName == "" || this.currentRegionName == null
            ? "全国"
            : this.currentRegionName) +
          " ] " +
          "<br>" +
          " 您查询的时间区间为：[ " +
          (this.selectBetweenTime == "" || this.selectBetweenTime == null
            ? "不限时间"
            : this.selectBetweenTime) +
          " ] " +
          "<br>" +
          "  平均薪酬为： " +
          this.totalData.salaryNum +
          "<br>" +
          " 职位总数为： " +
          this.totalData.companyNum;
        +`</div>`;

        this.$alert(content, "计算查询结果", {
          confirmButtonText: "确定",
          dangerouslyUseHTMLString: true,
        });
        this.listLoading = false;
      });
    },
    handlePageChange(currentPage) {
      this.tablePage.pageNum = currentPage;
      this.fetchData();
      // 在此刷新数据
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize;
      this.fetchData();
      // 在此刷新数据
    },
    onExportClick() {
      // 导出方法
      this.listLoading = true;
      const params = {
        id: this.$route.query.id,
        page: 1,
        perPage: 10000,
      };
      if (this.selectTime != "") {
        params.selectTime = this.selectTime;
      }
      if (this.regionList != []) {
        params.regionId = this.regionList[this.regionList.length - 1];
      }
      if (this.workYearValue != "") {
        params.selectValue = this.workYearValue;
      }
      if (this.selectBetweenTime != "") {
        params.selectBeginTime = this.selectBetweenTime[0];
        params.selectEndTime = this.selectBetweenTime[1];
      }

      if (this.orderByColumn != "" && this.orderBy != "") {
        params.orderByColumn = this.orderByColumn;
        params.orderBy = this.orderBy == "ascending" ? "asc" : "desc";
      } else {
        params.orderByColumn = "salary_num";
        params.orderBy = "desc";
      }
      if (this.groupByColumn != null && this.groupByColumn != "") {
        params.groupByColumn = this.groupByColumn;
        params.regionName =
          this.currentRegionName != "" && this.currentRegionName != null
            ? this.currentRegionName
            : "全国";
      }

      getWorkSalaryListExport(params)
        .then((result) => {
          const link = document.createElement("a"); // 创建a标签
          const blob = new Blob([result], { type: "application/vnd.ms-excel" }); // 设置文件流
          link.style.display = "none";
          // 设置连接
          link.href = URL.createObjectURL(blob); // 将文件流转化为blob地址
          link.download =
            (this.$route.query.name != undefined
              ? this.$route.query.name
              : "") + "工作经验薪酬数据统计表";
          document.body.appendChild(link);
          // 模拟点击事件
          link.click(); // 设置点击事件
          this.listLoading = false;
          window.URL.revokeObjectURL(link.href); // 释放掉blob对象
          document.body.removeChild(link); // 下载完成移除元素
        })
        .catch((err) => {
          console.log(err);
        });
    },
    sortChange(column) {
      this.orderByColumn = column.prop != null ? column.prop : "salary_num";
      this.orderBy = column.order != null ? column.order : "desc";
      this.fetchData();
      // 在此刷新数据
    },
    addGroupByColumn() {
      this.groupByColumn = "exp_code";
      this.fetchData();
    },
  },
};
</script>

<style scoped lang="scss">
/* .positionName {
  display: flex;
  width: 100vw;
  align-items: center;
  color: #333333;
  background-color: #edf6ff;
  height: 48px;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 12px;
  margin-left: -56px;
  padding: 0 55px;
} */
.list {
  /* height: 650px;
  overflow-y: auto; */
}
.app-container {
  /* width: 100%; */
  /* padding-right: 56px; */
  padding-top: 0px;
  overflow: hidden;
  position: relative;
  /* min-height: 720px; */
  /* max-height: calc(100vh - 100px); */
  /* background: linear-gradient(180deg, #eaf5ff 0%, #ffffff 100%); */
  /* /* background-image: url("https://upload.yl1001.com/upload/images/view?file=Q,tr--ap_8c=fney6Bg2IJzH69mz6q=xfFRO5e57Imp9e0psmHce_CdVSB9mv.png"); */
  /* background-size: 100% 200px;
  background-repeat: no-repeat; */
  /* border-radius: 10px 8px 8px 8px; */
  /* border: 0; */
  padding-bottom: 0px;
}
.app-content {
  padding-left: 0px;
}
.top-title {
  display: flex;
  margin: 40px 40px 10px 0px;
}
.tinyTitle {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #222;
  font-weight: bold;
  margin-right: 40px;

  .titleFlag {
    width: 5px;
    height: 15px;
    border-radius: 3px;
    background: #4880ff;
    margin-right: 12px;
  }
}
.echart {
  display: flex;
  position: relative;
  /* display: flow-root; */
  /* // max-height: calc(100vh - 192px); */
  // overflow-y: scroll;
  overflow: hidden;

  /* padding-right: 56px; */
  // &::-webkit-scrollbar {
  //   width: 4px;
  //   background-color: #fff;
  //   border-radius: 4px;
  //   height: 4px;
  // }
  // &::-webkit-scrollbar-thumb {
  //   background-color: #d8d8d8;
  //   border-radius: 4px;
  // }
}
.top-line {
  height: 1px;
  background-color: #cfd8f5;
  margin: -24px 0px 20px 180px;
}
.workBarChart {
  display: flex;
}

.search-container {
  /* margin-bottom: 24px; */
}
.pagination {
  margin-top: 24px;
}
::v-deep .el-table th > .cell {
  color: rgba(0, 0, 0, 0.85);
}
::v-deep .el-table th {
  background-color: #fafafa;
}
::v-deep .el-table .el-table__body-wrapper {
  border-color: rgb(239, 239, 239); /* 设置表格列的边框颜色 */
}
::v-deep .el-table {
  border-color: rgb(239, 239, 239); /* 设置表格列的边框颜色 */
}
::v-deep.el-table .el-table__header-wrapper .el-table__header th,
::v-deep.el-table .el-table__body-wrapper tbody .el-table__row td {
  border-color: rgb(239, 239, 239); /* 设置表格列的边框颜色 */
}
::v-deep.el-form--inline .el-form-item {
  margin-right: 24px;
}
::v-deep .el-tabs__item {
  height: 40px !important;
  color: #555;
  font-size: 16px;
}
::v-deep .el-tabs__item.is-active {
  color: #1574ff;
  font-weight: bold;
}
::v-deep .el-tabs__nav-wrap::after {
  background-color: transparent;
  height: 1px;
}
::v-deep .el-button--primary {
  color: #fff;
  background: #0b6eff;
  border-color: #0b6eff;
}
::v-deep .el-button--primary.is-plain {
  color: #409eff;
  background: #fff;
  border-color: #b3d8ff;
}
.filter-item {
  margin-bottom: 12px;
}
::v-deep .el-form-item {
  display: flex;
  align-items: center;
}
::v-deep .el-form-item__label {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 27px;
  min-width: 68px !important;
}
::v-deep .el-form-item__content {
  margin-left: 0 !important;
}

.toolTipGuide {
  display: flex;
}
.toolTipItems {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.stepImageContainer {
}
.stepImage {
  width: 264px;
  height: 149px;
}
.stepDesc {
  margin-top: 14px;
  font-size: 14px;
}
</style>
